// pagesMine/pages/houseApprove/houseApprove.js
import ajax from '../../../utils/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    parkLatitude: null,
    parkLongitude: null,
    houseTypeList: ['写字楼', '商铺', '土地'],
    /**
     * 详情id
     */
    detailId: null,
    /**
     * 提交认证是否可以点击
     */
    isSubmit: false,
    /**
     * 返回页面状态
     */
    backType: 0,
    /**
     * 表单对象
     */
    formData: {
      id: null, // 房产id
      gardenHomeId: null, // 所属园区id
      gardenHomeName: null,// 园区名称
      houseAgentId: null, // 经纪人id：可以解绑、更换或选择无经纪人；0无经纪人
      houseAgentName: null, // 经纪人名称
      houseArea: null, // 房屋实际面积
      housingAssessImage: [], // 房产图片id
      roomNumber: null, // 楼号.单元号.房号
      houseType: null, // 房屋类型：1写字楼；2商铺；3厂房；4仓库；5土地
      houseTypeName: null, // 房屋类型名称
      storeyHeight: null, // 楼层
      pattern: null,// 房屋格局
      orientation: null, // 朝向
      province: null, // 省
      city: null, // 地级市
      county: null, // 区县
      town: null, //街道、镇
      address: null, //详细地址
      buildingNo: null, // 楼号
      unitNo: null, // 单元
      roomNo: null, // 房号
    }
  },
  /**
   * 校验字段
   */
  isSubmitChange() {
    const { buildingNo, roomNo, unitNo, pattern, gardenHomeId, houseArea, orientation, houseType, housingAssessImage, address, storeyHeight } = this.data.formData;
    const boo = !(buildingNo && roomNo && unitNo && pattern && address && gardenHomeId && houseArea && orientation && houseType && storeyHeight && housingAssessImage.length)
    this.setData({ isSubmit: !boo })
  },
  /**
   * 房产地址 事件
   */
  addressEvent() {
    const { formData, parkLatitude, parkLongitude } = this.data
    wx.chooseLocation({
      latitude: parkLatitude,
      longitude: parkLongitude,
      complete: (location) => ajax.getQQMap().reverseGeocoder({
        location: { latitude: location.latitude, longitude: location.longitude },
        success: (res) => {
          const { address_component, address_reference } = res.result
          formData.province = address_component.province, formData.city = address_component.city, formData.county = address_component.district, formData.town = address_reference.town.title, formData.address = address_reference.town.title + address_component.street_number + address_reference.landmark_l2.title;
          this.setData({ formData })
          this.isSubmitChange()
        }
      })
    })
  },
  /**
   * 删除图片事件
   */
  deleteImageEvent(event) {
    const { index, item } = event.currentTarget.dataset;
    const { formData } = this.data
    wx.showModal({
      title: '提示',
      content: '确定删除该图片吗?',
      success: async (res) => {
        if (!res.confirm) return;
        if (item.id) await ajax.get(`/huosing/image/remove?id=${item.id}`)
        formData.housingAssessImage.splice(index, 1);
        ajax.showSuccess('操作成功!')
        this.setData({ formData })
        this.isSubmitChange()
      }
    })
  }, 
  /**
   * 选择框事件
   */
  pickerChange(event) {
    const key = event.currentTarget.dataset.key
    const { formData } = this.data
    if (key == 'houseTypeName') formData.houseType = event.detail.startIndex + 1;
    formData[key] = event.detail.startValue
    this.setData({ formData })
    this.isSubmitChange()
  },
  /**
   * input 变化事件
   */
  formItemChange(event) {
    const { formData } = this.data, key = event.currentTarget.dataset.key, value = key == 'buildingNo' || key == 'unitNo' || key == 'roomNo' ? event.detail.value || null : event.detail || null
    formData[key] = value
    this.setData({ formData })
    this.isSubmitChange()
  },
  /**
   * 上传房产证明图片
   */
  async uploadEvent() {
    const { formData } = this.data
    const imagePath = await ajax.chooseImage()
    const res = await ajax.uploadFile({ filePath: imagePath })
    const image = res.data.url, housingAssessId = formData.id
    if (housingAssessId) ajax.post('/huosing/image/add', { housingAssessId, image })
    formData.housingAssessImage.push({ image }), this.setData({ formData }), this.isSubmitChange()
  },
  /**
   * 房产认证详情
   */
  async getDetailRequest(id) {
    const { detailId, houseTypeList } = this.data
    const res = await ajax.get(`/my/house/assess/info?id=${id || detailId}`)
    const entity = res.data
    entity.houseTypeName = houseTypeList[entity.houseType - 1]
    entity.houseAgentName = entity.agent?.name || ''
    const [buildingNo, unitNo, roomNo] = entity.roomNumber.split(',')
    entity.buildingNo = buildingNo
    entity.unitNo = unitNo
    entity.roomNo = roomNo
    this.setData({ formData: entity, detailId: id || detailId })
    this.isSubmitChange()
  },
  /**
   * 提交事件
   */
  async submitEvent() {
    ajax.showLoading()
    const { detailId, backType } = this.data
    const formData = JSON.parse(JSON.stringify(this.data.formData))
    formData.roomNumber = `${formData.buildingNo},${formData.unitNo},${formData.roomNo}`;
    formData.checkStatus = detailId ? 0 : null
    // detailId ? true 调用修改接口 false 调用新增接口
    await ajax.post(detailId ? '/my/house/assess/update' : '/my/house/assess/add', formData).finally(() => wx.hideLoading())
    await ajax.showToast('提交成功, 请等待审核')
    detailId || backType == 1 ? wx.navigateBack() : wx.redirectTo({ url: '/pagesMine/pages/landlordManage/landlordManage' })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    options.detailId ? this.getDetailRequest(options.detailId) : null;
    this.data.backType = options.backType || 0
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const { parkEntity, brokerEntity, formData } = this.data
    if (parkEntity) {
      this.data.parkLatitude = parkEntity.latitude
      this.data.parkLongitude = parkEntity.longitude
      formData.gardenHomeId = parkEntity.id // 园区ID
      formData.gardenHomeName = parkEntity.gardenName || '' // 园区名称
      formData.province = parkEntity.province || ''
      formData.city = parkEntity.city || ''
      formData.county = parkEntity.county || ''
      formData.town = parkEntity.town || ''
      formData.address = `${parkEntity.town || ''}${parkEntity.address || ''}`
      this.data.parkEntity = null
      this.setData({ formData })
    }

    if (brokerEntity) {
      formData.houseAgentId = brokerEntity.id // 经纪人
      formData.houseAgentName = brokerEntity.name // 经纪人名称
      this.data.brokerEntity = null
      this.setData({ formData })
    }
    this.isSubmitChange()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})